/* global $*/

var baseURL = 'https://developer.cybozu.io';

$(function() {
  'use strict';
  // debug
  // var debugDate = new Date();
  // console.log(debugDate);

  adjustContentPosition();
  $(window).resize(function() {
    adjustContentPosition();
  });

  if ($('#page-homepage').length > 0) {
    homepageArticleList(baseURL + '/api/v2/help_center/sections/200129785/articles.json', '#APIUpdate', 5);
    homepageArticleList(baseURL + '/api/v2/help_center/sections/202364246/articles.json', '#sampleUpdate', 6);
    homepageCommunityPostList(10);
  }

  // header search box
  searchboxSwitch();


  // 検索フォームplaceholder書き換え
  $('form.search input[type="search"]').attr('placeholder', 'developer network内で検索');

  // コミュニティのボタンのラベル書き換え
  if ($('.community-header-subscribe').length > 0) {
    $('.topic-subscribe > a.dropdown-toggle').text('このトピックをフォロー')
      .prepend('<span class="fa fa-rss"></span>');
  }
  if ($('.post-subscribe').length > 0) {
    $('.post-header-subscribe > a.post-subscribe').text('このスレッドをフォロー')
      .prepend('<span class="fa fa-rss"></span>');
  }
  // セクションのボタンのラベル書き換え
  if ($('.section-header').length > 0) {
    $('.section-subscribe > a.dropdown-toggle').text('このセクションをフォロー')
      .prepend('<span class="fa fa-rss"></span>');
  }
  // 記事のボタンのラベル書き換え
  if ($('.article-subscribe').length > 0) {
    $('article > a.article-subscribe').text('この記事をフォロー')
      .prepend('<span class="fa fa-rss"></span>');
  }

  // vote-buttonにデフォルトで「はい」が入っているのを削除
  $.each($('.vote-button > a', '#page-community'), function() {
    $(this).removeAttr('title');
  });
  $.each($('.vote-button > a', '#page-article'), function() {
    $(this).removeAttr('title');
  });

  // 検索キーワード保持
  /* header search */
  if ($('.category-search .search-results').length > 0) {
    saveSearchWord();
  }

  // 記事コメント記入時処理
  $('.comment-form-controls > input', '.article').click(function() {
    postArticleComment();
  });
  searchboxSwitch();

  // Voteを獲得した数表示
  if ($('.profile-stats-counters').length > 0) {
    countVote();
  }
  // Follow countを獲得した数表示
  if ($('.dropdown-toggle').length > 0) {
    var pageUrl = document.URL;
    if (pageUrl.indexOf('202364246') > 0 || pageUrl.indexOf('200129785') > 0) {
      countFollow();
    }
  }

  // 記事ページAPI更新情報／サイト更新情報がフォローしているのが表示
  if ($('#page-article').length > 0) {
    articlepageFollowShow(200129785, '.subscribeAPI');
    articlepageFollowShow(202364246, '.subscribeSite');
  }

  // showMobileMenu
  $('#openMobileMenu').click(function(){
    $('#mobileMenu').fadeIn();
    $('body').css('position', 'fixed');
  });
  $('#closeMobileMenu').click(function(){
    $('#mobileMenu').hide();
    $('body').css('position', '');
  });

  $('#showMobileSideNav').click(function(){
    $('.sideNav').fadeIn();
    $('body').css('position', 'fixed');
  });
  $('#closeMobileSideNav').click(function(){
    $('.sideNav').hide();
    $('body').css('position', '');
  })
});

/* ------------------------
 Global
 -------------------------*/
/* adjust content position with header height. */
function adjustContentPosition() {
  $('main').css('paddingTop', $('header.header').outerHeight());
}

function htmlspecialchars(ch){
    ch = ch.replace(/&/g,"&amp;");
    ch = ch.replace(/"/g,"&quot;");
    ch = ch.replace(/'/g,"&#039;");
    ch = ch.replace(/</g,"&lt;");
    ch = ch.replace(/>/g,"&gt;");
    return ch;
}

/* ------------------------
 ホームページ
 -------------------------*/
/* 下部3カラムの記事リスト */
function homepageArticleList(jsonUrl, displayTarget, limit) {
  $.ajax({
    url: jsonUrl + '?sort_by=created_at&sort_order=desc',
    dataType: 'json',
    async: true,
    success: function(json) {
      data = json;
    }
  }).then(function(data) {
    var articles = data.articles;
    var articlesUL = $('<ul class="list-articles"></ul>');
    var articleLI;
    var articleURL;
    var articleUpdate;
    var articleTitle;
    var sectionLink;

    articles = articles.slice(0, limit);

    $.each(articles, function(index, article) {
      articleURL = article.html_url;
      articleUpdate = article.created_at.substr(0, 10)
        .replace(/-/g, '/');
      articleTitle = article.name;
      articleLI = $('<li><a style="margin-left:0px;" href="' + articleURL + '">' + articleTitle + '</a></li>');
      articlesUL.append(articleLI);
    });
    $(displayTarget).append(articlesUL);

    /* --------------------------------------
      follow homepage show
    -------------------------------------- */
    sectionLink = $('<div style="text-align:right;"><a href="' + baseURL + '/hc/ja/sections/'
      + articles[0].section_id
      + '">すべて見る <i class="fa fa-angle-right fa-1" aria-hidden="true"></i></a></div>');
    switch (displayTarget) {
      case '#APIUpdate':
        $('#APIUpdate').append(sectionLink);
        homepageFollowShow(articles[0].section_id, '.subscribeAPI');
        break;
      case '#sampleUpdate':
        $('#sampleUpdate').append(sectionLink);
        homepageFollowShow(articles[0].section_id, '.subscribeSite');
        break;
      default:
        break;
    }
  });
}

function homepageCommunityPostList(limit) {
  $.ajax({
    url: baseURL + '/api/v2/community/posts.json',
    dataType: 'json',
    async: true,
    success: function(json) {
      data = json;
    }
  }).then(function(data) {
    var posts = data.posts;
    var postsUL = $('<ul class="list-posts"></ul>');
    var postLI;
    var postURL;
    var postTitle;
    var postCommentCount;

    posts = posts.slice(0, limit);

    $.each(posts, function(index, post) {
      postURL = post.html_url;
      postTitle = post.title;
      var escapedPostTitle = htmlspecialchars(postTitle);
      postCommentCount = post.comment_count;
      postLI = $('<li><span class="commentCount fa fa-comments"> ' + postCommentCount + '</span><a href="'
        + postURL + '">' + escapedPostTitle + '</a></li>');
      if (post.topic_id == '115000025163') {
        postLI = $('<li><span class="commentCount fa fa-book"> ' + postCommentCount + '</span><a href="'
          + postURL + '">' + escapedPostTitle + '</a></li>');
      }
      postsUL.append(postLI);
    });

    $('.top-communityPost-list').append(postsUL);

  });
}

/* ------------------------------------------------------------------------
 sideNavのメニュー展開 (サイドメニューがセクションになっている記事)
 -------------------------------------------------------------------------*/
function sideNavMenuSection(jsonFileName) {
  'use strict';
  var filename = jsonFileName;
  var currentURL = window.location.href;
  var paths = currentURL.split('/');
  var currentID = paths[paths.length - 1].split('-')[0];

  $.ajax({
    url: baseURL + '/api/v2/help_center/articles/' + currentID + '.json',
    dataType: 'json',
    async: true,
    success: function(resp) {
      var secid = resp.article.section_id;
      sideNavMenu(filename, secid.toString());
    }
  });
}

/* ------------------------
 sideNavのメニュー展開
 @jsonFileName： 対象のサイドメイニューのJSON URL
 @sectionID： Tipsの記事などメニューがセクション単位の記事の場合は
             sideNavMenuSection()経由でsectionIDを指定してCallする
 -------------------------*/
function sideNavMenu(data, sectionID) {
  'use strict';
  var currentURL = window.location.href;
  var paths = currentURL.split('/');
  var currentID = sectionID || paths[paths.length - 1].split('-')[0]; // sectionIDがある場合はsectionID優先

  var sideNav = $('#sideNav');
  var categories = data.category;
  var sections;
  var sectionUL;
  var sectionLI;
  var articleUL;
  var articleLI;

  $.each(categories, function(categoryCount, category) {
    sideNav.append('<h4 class="sideNav-categoryName">' + category.name + '</h4>');

    sections = category.section;

    // sections
    $.each(sections, function(sectionCount, section) {
      sectionUL = $('<ul class="sideNav-section"></ul>');
      sectionLI = $('<li><a href="javascript:" title="' + section.name + '">' + section.name + '</a></li>');

      articleUL = $('<ul class="sideNav-articles"></ul>');

      var currentSection = section.article.filter(function(item, index) {
        if (String(item.id) === currentID) {
          sectionUL.addClass('currentSection open');
        }
      });

      // articles
      $.each(section.article, function(articleCount, article) {
        if (String(article.id) === currentID) {
          articleLI = $('<li><a class="sideNav-article currentArticle" href="' + article.url
            + '" title="' + article.name + '">' + article.name + '</a></li>');
        } else {
          articleLI = $('<li><a class="sideNav-article" href="' + article.url + '" title="'
            + article.name + '">' + article.name + '</a></li>');
        }
        articleUL.append(articleLI);
      });

      sectionLI.append(articleUL);
      sectionUL.append(sectionLI);
      sideNav.append(sectionUL);

      // メニュー開閉
      $('.sideNav-section > li > a').off('click');
      $('.sideNav-section > li > a').click(function() {
        $(this).closest('.sideNav-section').toggleClass('open');
      });
    });

  });
}

/* ------------------------
  記事ページ
------------------------ */
function copyBtn() {
  'use strict';
  var gists = $('.gist');

  $('pre .article-body').wrap('<div class="preWrap"></div>');
  var planeCode = $('.preWrap');

  $.each(gists, function(index, gistContents) {
    $(this).attr('id', 'gist-' + index);

    var button = '<div class="copyBtn" data-clipboard-target="#gist-' + index
      + ' div"><span class="fa fa-copy"></span> Copy<span class="tooltip">クリップボードにコピーしました</span></div>';
    $(this).append(button);
  });

  $.each(planeCode, function(index, codeContents) {
    $(this).attr('id', 'pre-' + index);

    var button = '<div class="copyBtn" data-clipboard-target="#pre-' + index
      + ' pre"><span class="fa fa-copy"></span> Copy<span class="tooltip">クリップボードにコピーしました</span></div>';
    $(this).append(button);
  });

  var clipboard = new Clipboard('.copyBtn');
  clipboard.on('success', function(e) {
    $(e.trigger).addClass('copied');
    setTimeout(function() {
      $(e.trigger).removeClass('copied');
    }, 1200); // cssのfadeの値とあわせる
    e.clearSelection();
  });
}

function saveSearchWord() {
  'use strict';
  var match = location.search.match(/query=(.*?)(&|$)/);
  if (match) {
    $('#query').val(decodeURIComponent(match[1]));
  }
}

function postArticleComment() {
  'use strict';
  var cdata = {
    url: location.href.split('?')[0],
    name: HelpCenter.user.name,
    email: HelpCenter.user.email,
    title: encodeURIComponent($('.article-header > h1').text().trim()),
    comment: encodeURIComponent($('#comment_body_ifr').contents().find('#tinymce').html())
  };

  $.ajax({
    url: 'https://functions9a231b73.azurewebsites.net/api/'
    + 'CopyZendeskArticleComment?code=7ZzzWoakW0aH51wjskWVyAQT7tSRelRKSoWERh95bzK21UDOTRu/Rg==',
    type: 'POST',
    data: cdata
  });
}

/* ------------------------
  検索 header
------------------------ */
function searchboxSwitch() {
  'use strict';
  $("#showHeaderSearchButton").click(function(){
    $("#showHeaderSearchButton").hide();
    $("#expandSearch, #closeSearch").fadeIn("fast");
    $("#expandSearch #query").focus();
  })

  $("#expandSearch #query").focusout(function(){
    $("#closeSearch").hide();
    $("#expandSearch").fadeOut("fast");
    $("#showHeaderSearchButton").fadeIn("fast");
  });

}

/* ------------------------
  Voteを獲得した数表示
------------------------ */
function countVote() {
  'use strict';
  var pageUrl = document.URL;
  var user = pageUrl.substr(pageUrl.lastIndexOf('/') + 1);
  var myId, myRole;
  var userId = '';

  if (user.indexOf('-') < 0) {
    userId = user;
  } else {
    userId = user.substr(0, user.indexOf('-'));
  }

  $.ajax({
    url: baseURL + '/api/v2/users/me.json',
    dataType: 'json',
    async: true,
    success: function(resp) {
      myId = resp.user.id;
      myRole = resp.user.role;
      var voteSum = 0;

      // 自分あるいはadminの場合に表示する
      if (parseInt(myId, 0) === parseInt(userId, 0) || myRole === 'admin') {
        $.ajax({
          url: baseURL + '/api/v2/community/users/' + userId + '/posts.json',
          dataType: 'json',
          async: false,
          success: function(resp) {
            var posts = resp.posts;
            for (var i = 0; i < posts.length; i++) {
              voteSum += posts[i]['vote_count'];
            }
          }
        });

        $.ajax({
          url: baseURL + '/api/v2/community/users/' + userId + '/comments.json',
          dataType: 'json',
          async: false,
          success: function(resp) {
            var comments = resp.comments;
            for (var i = 0; i < comments.length; i++) {
              voteSum += comments[i]['vote_count'];
            }
          }
        });
        $('.profile-stats-counters').append('<li class="stat"><span class="stat-label">'
          + 'いいね獲得</span><span class="stat-value">' + voteSum + '</span></li>');
      }
    }
  });
}

/* ---------------------------------
  follow countを獲得した数表示
--------------------------------- */
function countFollow() {
  'use strict';
  var pageUrl = document.URL;
  var myRole;
  var section_id = pageUrl.substr(pageUrl.lastIndexOf('/') + 1).split('-')[0].split('#')[0];
  $.ajax({
    url: baseURL + '/api/v2/users/me.json',
    dataType: 'json',
    async: true,
    success: function(resp) {
      myRole = resp.user.role;
      if (myRole === 'admin') {
        $.ajax({
          url: baseURL + '/api/v2/help_center/ja/sections/'
          + section_id + '/subscriptions.json',
          dataType: 'json',
          async: true,
          success: function(resp) {
            var myCount = resp.count;
            $('.section-subscribe').after(
              '<div style="display: inline-block; margin-left: 10px; border-radius: 4px;'
              + ' background-color: #eee"><span style="display: inline-block; color: #158ec2;'
              + ' padding: 5px 10px">' + myCount + ' Followers</span></div>');
          }
        });
      }
    }
  });
}

function checkFlow(resp, myId) {
  'use strict';
  var thisPageLength;
  var thisPageSubscriptions = [];
  var thisUserId;
  var includeComments;
  var homepageFollowInfo = [0, null];
  var isIncludeComments = 0;
  var isNotIncludeComments = 0;
  var id;
  thisPageLength = resp.subscriptions.length;
  thisPageSubscriptions = resp.subscriptions;
  for (var i = 0; i < thisPageLength; i++) {
    thisUserId = thisPageSubscriptions[i].user_id;
    if (thisUserId === myId) {
      includeComments = thisPageSubscriptions[i].include_comments;
      id = thisPageSubscriptions[i].id;
      if (includeComments === true) {
        isIncludeComments = 1;
      } else {
        isNotIncludeComments = 2;
      }
      break;
    }
  }
  homepageFollowInfo[0] = isIncludeComments + isNotIncludeComments;
  homepageFollowInfo[1] = id;
  return homepageFollowInfo;
}


function homepageFollowSelect(selectItem, classId) {
  'use strict';
  switch (selectItem) {
    case 'noComments':
      $(classId + ' .new-article').attr('aria-selected', 'true');
      $(classId + ' .new-article-comments').attr('aria-selected', 'false');
      break;
    case 'hasComments':
      $(classId + ' .new-article').attr('aria-selected', 'false');
      $(classId + ' .new-article-comments').attr('aria-selected', 'true');
      break;
    case 'noFollow':
      $(classId + ' .new-article, ' + classId + ' .new-article-comments').attr('aria-selected', 'false');
      $(classId + ' .stop-following').hide();
      $(classId).prev().html('<span class="fa fa-rss"></span> フォローする');
      $(classId).parent().find('.dropdown-toggle').removeAttr('style');
      break;
    case 'hasFollowed':
      $(classId + ' .stop-following').show();
      $(classId).prev().html('<span class="fa fa-rss"></span> フォロー中');
      $(classId).parent().find('.dropdown-toggle').css({
        'background-color': '#fff', 'color': '#3fa7df', 'border': '2px solid #3fa7df'});
      break;
    case 'infoFollowed':
      $(classId).parent().prev().show();
      $(classId).parent().prev().find('.notification-text').text('このフォローしています。');
      break;

    case 'infoNoFollow':
      $(classId).parent().prev().show();
      $(classId).parent().prev().find('.notification-text').text('このフォローしていません。');
      break;
    default:
      break;
  }
}

function pageFollowUpdateSubscriptionId(section_id, myId) {
  'use strict';
  var flag = [0, null];
  var nextPage = baseURL + '/api/v2/help_center/ja/sections/'
    + section_id + '/subscriptions.json?per_page=100';
  $.ajax({
    url: nextPage,
    dataType: 'json',
    async: false,
    success: function(resp) {
      flag = checkFlow(resp, myId);
      if (flag[0] > 0) {return;}
      nextPage = resp.next_page;
      for (var j = 2; j <= resp.page_count; j++) {
        if (nextPage === null) {break;}
        $.ajax({
          url: nextPage + '&per_page=100',
          dataType: 'json',
          async: false,
          success: function(resp) {
            nextPage = resp.next_page;
            flag = checkFlow(resp, myId);
          }
        });
        if (flag[0] > 0) {break;}
      }
    }
  });
  return flag;
}

/* ------------------------
  follow homepage show
------------------------ */
function homepageFollowShow(section_id, classId) {
  'use strict';
  var myId;
  var subscriptionId;

  $.ajax({
    url: baseURL + '/api/v2/users/me.json',
    dataType: 'json',
    async: true,
    success: function(resp) {
      myId = resp.user.id;
      if (!myId) {
        $(classId).parent().find('button').attr({
          'href': '#', 'data-auth-action': 'signin', 'aria-selected': 'false'});
        $(classId).hide();
        return;
      }

      var flag = pageFollowUpdateSubscriptionId(section_id, myId);
      subscriptionId = flag[1];
      if (flag[0] === 1) {
        homepageFollowSelect('hasComments', classId);
        homepageFollowSelect('hasFollowed', classId);
      } else if (flag[0] === 2) {
        homepageFollowSelect('noComments', classId);
        homepageFollowSelect('hasFollowed', classId);
      } else {
        homepageFollowSelect('noFollow', classId);
      }
      return;
    }
  });

  $(classId + ' a.new-article').click(function() {
    $.ajax({
      type: 'POST',
      url: baseURL + '/api/v2/help_center/sections/'
      + section_id + '/subscriptions.json',
      data: {
        'subscription': {'source_locale': 'ja', 'include_comments': false}},
      dataType: 'json',
      async: false,
      success: function(resp) {
        homepageFollowSelect('noComments', classId);
        homepageFollowSelect('hasFollowed', classId);
        homepageFollowSelect('infoFollowed', classId);
      }
    });
  });

  $(classId + ' a.new-article-comments').click(function() {
    $.ajax({
      type: 'POST',
      url: baseURL + '/api/v2/help_center/sections/'
      + section_id + '/subscriptions.json',
      data: {'subscription': {'source_locale': 'ja', 'include_comments': true}},
      dataType: 'json',
      async: false,
      success: function(resp) {
        homepageFollowSelect('hasComments', classId);
        homepageFollowSelect('hasFollowed', classId);
        homepageFollowSelect('infoFollowed', classId);
      }
    });
  });

  $(classId + ' a.stop-following').click(function() {
    var flag = pageFollowUpdateSubscriptionId(section_id, myId);
    subscriptionId = flag[1];
    $.ajax({
      type: 'DELETE',
      url: baseURL + '/api/v2/help_center/sections/'
      + section_id + '/subscriptions/' + subscriptionId + '.json',
      dataType: 'json',
      async: false,
      success: function(resp) {
        homepageFollowSelect('noFollow', classId);
        homepageFollowSelect('infoNoFollow', classId);
      }
    });
  });
}

/* ------------------------
  follow articlepage show
------------------------ */
function articlepageFollowSelect(selectItem, classId) {
  'use strict';
  switch (selectItem) {
    case 'noComments':
      $(classId + ' .new-article').attr('aria-selected', 'true');
      $(classId + ' .new-article-comments').attr('aria-selected', 'false');
      break;
    case 'hasComments':
      $(classId + ' .new-article').attr('aria-selected', 'false');
      $(classId + ' .new-article-comments').attr('aria-selected', 'true');
      break;
    case 'noFollow':
      $(classId + ' .new-article, ' + classId + ' .new-article-comments').attr('aria-selected', 'false');
      $(classId + ' .stop-following').hide();
      break;
    case 'hasFollowed':
      $(classId + ' .stop-following').show();
      break;
    default:
      break;
  }
}

function articlepageFollowShow(section_id, classId) {
  'use strict';
  var myId;
  var flag = [0, null];

  $.ajax({
    url: baseURL + '/api/v2/users/me.json',
    dataType: 'json',
    async: true,
    success: function(resp) {
      myId = resp.user.id;
      if (!myId) { return; }

      flag = pageFollowUpdateSubscriptionId(section_id, myId);

      if (flag[0] === 1) {
        articlepageFollowSelect('hasComments', classId);
        articlepageFollowSelect('hasFollowed', classId);
      } else if (flag[0] === 2) {
        articlepageFollowSelect('noComments', classId);
        articlepageFollowSelect('hasFollowed', classId);
      } else {
        articlepageFollowSelect('noFollow', classId);
      }
      return;
    }
  });
}
